package com.lin.linchatgpt.service.impl;


import cn.hutool.crypto.digest.MD5;
import com.lin.linchatgpt.entity.User;
import com.lin.linchatgpt.entity.dto.LoginDTO;
import com.lin.linchatgpt.entity.table.UserTableDef;
import com.lin.linchatgpt.exception.LinException;
import com.lin.linchatgpt.mapper.UserMapper;
import com.lin.linchatgpt.service.UserService;
import com.lin.linchatgpt.utils.ResultCode;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;


/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/6/12 21:47
 * @Description
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public boolean register(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserTableDef.USER.EMAIL.eq(user.getEmail()));

        // 判断该邮箱在数据库中是否存在，是则判断是否激活，否则保存
        if (this.count(queryWrapper) > 0) {
            // 未激活的邮箱可以注册，并且更新用户信息，发送激活邮件，激活后可以登录，否则不可以登录，
            queryWrapper.where(UserTableDef.USER.STATUS.in(1, 2));
            if (this.count(queryWrapper) > 0) {
                throw new LinException(ResultCode.EMAIL_IS_EXISTS, "该邮箱已经被注册");
            }
            // 未激活的邮箱可以重复注册
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.where(UserTableDef.USER.EMAIL.eq(user.getEmail()));
            wrapper.where(UserTableDef.USER.STATUS.eq(0));
            user.setPassword(MD5.create().digestHex(user.getPassword()));
            return this.update(user, wrapper);
        }
        user.setPassword(MD5.create().digestHex(user.getPassword()));
        return this.save(user);
    }




    @Override
    public User login(LoginDTO loginDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.where(UserTableDef.USER.EMAIL.eq(loginDTO.getEmail()));
        queryWrapper.where(UserTableDef.USER.PASSWORD.eq(MD5.create().digestHex(loginDTO.getPassword())));

        return this.getOne(queryWrapper);
    }
}
